<template>
  <div class="app-container">
    <el-row :gutter="10" class="test_header" type="flex" align="middle" justify="start" v-if="!isMobile">
      <el-col :span="1.5" :xs="24">
        <el-button type="primary" plain icon="el-icon-plus" :style="{
          backgroundColor: theme,
          borderColor: theme,
          fontWeight: 'bold',
          color: '#fff',
          width: isMobile ? '100%' : 'auto',
          marginBottom: isMobile ? '10px' : '0'
        }" @click="handleAdd" v-hasPermi="['course:course:add']">新增节点
        </el-button>
      </el-col>

    </el-row>

    <!-- 移动端头部 -->
    <div class="mobile-header" v-if="isMobile">
      <div class="page-title">{{ type === 'add' ? '新增课程' : '编辑课程' }}</div>
      <div class="mobile-back" @click="cancel">
        <i class="el-icon-arrow-left"></i>
      </div>
    </div>

    <!-- 骨架屏 -->
    <mobile-skeleton v-if="loading && isMobile" type="form" :count="5" :showPagination="false" />
    
    <el-table v-loading="loading" :data="categoryList" row-key="id" :stripe="true"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      :class="{'mobile-table': isMobile}" size="mini">
      <el-table-column prop="name" label="课程名称" :show-overflow-tooltip="true"></el-table-column>

      <el-table-column prop="sort" label="排序" width="60" v-if="!isMobile"></el-table-column>
      <el-table-column label="操作" :width="isMobile ? 120 : 200">
        <template slot-scope="scope">
          <el-row :gutter="10" style="width:50%;" type="flex" justify="center" :class="{'mobile-actions': isMobile}">
            <el-col :span="1.5" :xs="8">
              <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                <span @click="handleUpdate(scope.row)" :style="{ color: theme, cursor: 'pointer' }"
                  v-hasPermi="['course:course:put']">
                  <svg-icon icon-class="editor" style="font-size: 17px" />
                </span>
              </el-tooltip>
            </el-col>
            <el-col :span="1.5" :xs="8">
              <el-tooltip class="item" effect="dark" content="新增" placement="top">
                <span @click="handleAdd(scope.row)" :style="{ color: theme, cursor: 'pointer' }"
                  v-hasPermi="['course:course:add']">
                  <i class="el-icon-plus" style="font-size: 17px" />
                </span>
              </el-tooltip>
            </el-col>
            <el-col :span="1.5" :xs="8">
              <el-tooltip class="item" effect="dark" content="删除" placement="top">
                <span @click="handleDelete(scope.row)" :style="{ color: 'red', cursor: 'pointer' }"
                  v-hasPermi="['course:course:delete']">
                  <svg-icon icon-class="del" style="font-size: 17px" />
                </span>
              </el-tooltip>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <!-- 移动端卡片视图 -->
    <div v-if="isMobile" class="mobile-card-view">
      <el-card v-for="(item, index) in categoryList" :key="index" class="mobile-card" shadow="hover">
        <div slot="header" class="card-header">
          <span>{{ item.name }}</span>
          <div class="card-actions">
            <span @click="handleUpdate(item)" :style="{ color: theme, cursor: 'pointer', marginRight: '10px' }"
              v-hasPermi="['course:course:put']">
              <svg-icon icon-class="editor" style="font-size: 17px" />
            </span>
            <span @click="handleAdd(item)" :style="{ color: theme, cursor: 'pointer', marginRight: '10px' }"
              v-hasPermi="['course:course:add']">
              <i class="el-icon-plus" style="font-size: 17px" />
            </span>
            <span @click="handleDelete(item)" :style="{ color: 'red', cursor: 'pointer' }"
              v-hasPermi="['course:course:delete']">
              <svg-icon icon-class="del" style="font-size: 17px" />
            </span>
          </div>
        </div>
        <div class="card-content">
          <p><strong>排序：</strong>{{ item.sort }}</p>
          <div v-if="item.children && item.children.length > 0" class="children-list">
            <p><strong>子节点：</strong></p>
            <ul>
              <li v-for="(child, childIndex) in item.children" :key="childIndex">
                {{ child.name }}
              </li>
            </ul>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" :visible.sync="open" :width="isMobile ? '95%' : '600px'" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :class="{'mobile-form': isMobile}">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级课程">
              <treeselect v-model="form.parentId" :options="menuOptions" :normalizer="normalizer" :show-count="true"
                placeholder="选择上级课程" />
            </el-form-item>
          </el-col>

          <el-col :span="12" :xs="24">
            <el-form-item label="课程名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入课程名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="显示排序" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="12">
                  <el-form-item v-if="form.menuType != '2'" label="显示状态">
                    <el-radio-group v-model="form.visible">
                      <el-radio v-for="dict in visibleOptions" :key="dict.dictValue" :label="dict.dictValue">{{
                        dict.dictLabel
                      }}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col> -->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" :class="{'mobile-dialog-footer': isMobile}">
        <el-button type="primary" @click="submitForm" :style="{
          backgroundColor: theme,
          borderColor: theme,
          width: isMobile ? '45%' : 'auto'
        }">确 定</el-button>
        <el-button @click="cancel" :style="{
          width: isMobile ? '45%' : 'auto'
        }">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
import variables from "@/assets/styles/variables.scss";
import {
  categoryList,
  categoryTree,
  updateCategory,
  addCategory,
  delCategory,
  getCategory,
  courseDetail,
  updateCourse,
  addCourse,
  listCourse,
} from "@/api/vadmin/course/course";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import IconSelect from "@/components/IconSelect";
import { isMobileViewport, addViewportChangeListener, removeViewportChangeListener } from '@/utils/device';
// 引入骨架屏组件
import MobileSkeleton from "@/components/MobileSkeleton";

export default {
  name: "Menu",
  components: { Treeselect, IconSelect, MobileSkeleton },

  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 菜单表格树数据
      categoryList: [],
      // 总条数
      total: 0,
      // 菜单树选项
      menuOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 显示状态数据字典
      visibleOptions: [
        { dictValue: true, dictLabel: "显示" },
        { dictValue: false, dictLabel: "不显示" },
      ],
      // 菜单状态数据字典
      statusOptions: [
        { dictValue: 1, dictLabel: "正常" },
        { dictValue: 0, dictLabel: "停用" },
      ],
      // 菜单类型数据字典
      menuTypeOptions: [
        { dictValue: 0, dictLabel: "目录" },
        { dictValue: 1, dictLabel: "菜单" },
        { dictValue: 2, dictLabel: "按钮" },
      ],

      // 查询参数
      queryParams: {
        name: undefined,
        visible: undefined,
        page: 1,
        page_size: 1000,
      },
      // 表单参数
      form: {},
      screenWidth: document.body.clientWidth,
      // 表单校验
      rules: {
        name: [
          { required: true, message: "课程名称不能为空", trigger: "blur" },
        ],
        sort: [
          { required: true, message: "课程顺序不能为空", trigger: "blur" },
        ],
      },
      isMobile: false,
      mediaQueryList: null,
      mediaQueryHandler: null,
      type: 'add',
    };
  },

  computed: {
    ...mapState(["settings"]),
    variables() {
      return variables;
    },
    theme() {
      return this.$store.state.settings.theme;
    },
  },

  watch: {
    screenWidth(val) {
      this.screenWidth = val;
    }
  },

  created() {
    // 初始化移动端检测
    this.mediaQueryList = window.matchMedia('(max-width: 768px)');
    // 初始化isMobile状态
    this.isMobile = this.mediaQueryList.matches;
    // 添加媒体查询监听器
    this.mediaQueryHandler = (e) => {
      this.isMobile = e.matches;
    };
    this.mediaQueryList.addListener(this.mediaQueryHandler);
    
    // 获取数据
    this.loading = true;
    this.getCategory();
    if (this.$route.params.id) {
      this.type = "edit";
      this.getCourse();
    } else {
      this.loading = false;
    }
  },

  beforeDestroy() {
    // 移除媒体查询监听器
    if (this.mediaQueryList) {
      this.mediaQueryList.removeListener(this.mediaQueryHandler);
    }
  },

  methods: {
    handleResize() {
      this.screenWidth = document.body.clientWidth;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        parentId: 0,
        name: undefined,
        sort: undefined,
        // interface_method: this.selectDictDefault(this.interfaceMethodOptions),
        // visible: this.selectDictDefault(this.visibleOptions),
        // status: this.selectDictDefault(this.statusOptions),
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.id) {
        this.form.parentId = row.id;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加课程";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      getCategory(row.id).then((response) => {
        // console.log(9999, response);
        this.form = response;
        this.open = true;
        this.title = "修改课程";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.type === "edit") {
            updateCourse(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.cancel();
              this.loading = false;
            }).catch(() => {
              this.loading = false;
            });
          } else {
            addCourse(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.cancel();
              this.loading = false;
            }).catch(() => {
              this.loading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除名称为"' + row.name + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delCategory(row.id);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 查询菜单列表 */
    getList() {
      this.loading = true;
      categoryList(this.queryParams).then((response) => {

        this.categoryList = this.handleTree(response, "id");

        this.total = response.count;
        // console.log("菜单", this.menuList);
        this.loading = false;
      });
    },
    /** 获取课程分类数据 */
    getCategory() {
      this.loading = true;
      categoryList(this.queryParams).then((response) => {
        this.categoryList = this.handleTree(response, "id");
        this.total = response.count;
        this.loading = false;
      });
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      // console.log("菜单结构", node);
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children,
      };
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      categoryTree({ page_size: 10000 }).then((response) => {
        // console.log("树结构", response);
        this.menuOptions = [];
        const menu = { id: 0, label: "主类目", children: [] };
        menu.children = this.handleTree(response, "id");
        // console.log("结果》〉》〉", menu);
        this.menuOptions.push(menu);
      });
    },

    /** 接口路径变化，必须斜杠开头，不能斜杠结尾*/
    InterfacePathChange() {
      if (this.form.interface_path.length === 0) {
        this.form.perms = "";
        return;
      }
      if (this.form.interface_path.indexOf("/") !== 0) {
        this.form.interface_path = "/" + this.form.interface_path;
      }
      if (!this.form.interface_path.endsWith("/")) {
        this.form.interface_path = this.form.interface_path + "/";
      }
      this.CreatePerms();
    },
    /** 自动生成权限标识 */
    CreatePerms() {
      let res = this.form.interface_path + ":" + this.form.interface_method;
      this.form.perms = res
        .toLocaleLowerCase()
        .replace(/(\/)/g, ":")
        .replace(/(::)/g, ":")
        .replace(/(^:)|(:$)/g, "");
    },
    getCourse() {
      this.loading = true;
      courseDetail(this.$route.params).then((response) => {
        this.form = response;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.mobile-toolbar {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15px;
}

.mobile-table {
  font-size: 12px;

  /deep/ .el-table__header-wrapper,
  /deep/ .el-table__body-wrapper {
    font-size: 12px;
  }

  /deep/ .cell {
    padding: 5px 8px;
  }
}

.mobile-actions {
  display: flex;
  justify-content: space-around;
  width: 100% !important;
}

.mobile-card-view {
  margin-top: 15px;
  
  .mobile-card {
    margin-bottom: 15px;
    border-radius: 8px;
    
    /deep/ .el-card__header {
      padding: 12px 15px;
    }
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      span {
        font-weight: bold;
        font-size: 16px;
      }
      
      .card-actions {
        display: flex;
      }
    }
    
    .card-content {
      padding: 5px 0;
      
      p {
        margin: 8px 0;
        font-size: 14px;
      }
      
      .children-list {
        margin-top: 10px;
        
        ul {
          padding-left: 15px;
          margin-top: 5px;
          
          li {
            margin-bottom: 5px;
            font-size: 14px;
          }
        }
      }
    }
  }
}

.mobile-form {
  .el-form-item {
    margin-bottom: 15px;
  }
  
  /deep/ .vue-treeselect {
    font-size: 14px;
  }
}

.mobile-dialog-footer {
  display: flex;
  justify-content: space-between;
}

/* 移动端样式 */
.mobile-header {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  height: 50px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 16px;
  
  .page-title {
    font-size: 18px;
    font-weight: bold;
  }
  
  .mobile-back {
    position: absolute;
    left: 16px;
    font-size: 20px;
    cursor: pointer;
  }
}

.mobile-form {
  padding: 16px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  .el-form-item__label {
    padding-bottom: 8px;
    font-weight: bold;
  }
  
  .el-button {
    margin-top: 8px;
    width: 100%;
  }
}

@media screen and (max-width: 768px) {
  .app-container {
    padding: 0;
  }
  
  .el-form-item {
    margin-bottom: 15px;
    
    /deep/ .el-form-item__label {
      padding-bottom: 8px;
      font-size: 15px;
    }
  }
  
  .el-input, .el-select {
    width: 100%;
    
    /deep/ .el-input__inner {
      height: 40px;
      border-radius: 8px;
      font-size: 15px;
    }
  }
  
  .el-textarea {
    /deep/ .el-textarea__inner {
      border-radius: 8px;
      padding: 10px;
      font-size: 15px;
    }
  }
  
  .el-button {
    width: 45%;
    height: 40px;
    font-size: 16px;
    margin: 0 5px;
  }
  
  .form-container {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
    padding: 15px;
    margin-bottom: 15px;
  }
  
  .header-container {
    margin-bottom: 20px;
    
    .section-title {
      font-size: 18px;
      font-weight: 500;
      margin-bottom: 10px;
      color: var(--theme);
    }
    
    .back-link {
      display: flex;
      align-items: center;
      padding: 8px 15px;
      background-color: #f5f7fa;
      border-radius: 8px;
      font-size: 14px;
      color: #606266;
      margin-top: 10px;
      cursor: pointer;
      
      i {
        margin-right: 5px;
      }
    }
  }
  
  .footer-actions {
    display: flex;
    justify-content: space-around;
    margin-top: 25px;
    padding-top: 15px;
    border-top: 1px dashed #ebeef5;
  }
  
  /deep/ .vue-treeselect__control {
    height: 40px;
    border-radius: 8px;
    
    .vue-treeselect__single-value {
      line-height: 40px;
      font-size: 15px;
    }
    
    .vue-treeselect__placeholder {
      line-height: 40px;
      font-size: 15px;
    }
  }
  
  /deep/ .vue-treeselect__menu {
    border-radius: 8px;
    
    .vue-treeselect__option {
      padding: 8px 15px;
      font-size: 15px;
    }
  }
  
  /deep/ .el-dialog {
    width: 90% !important;
    margin: 0 auto !important;
    border-radius: 12px;
    overflow: hidden;
    
    .el-dialog__header {
      padding: 15px;
      background-color: #f5f7fa;
      text-align: center;
      font-weight: bold;
    }
    
    .el-dialog__body {
      padding: 15px;
      max-height: 70vh;
      overflow-y: auto;
    }
    
    .el-dialog__footer {
      padding: 10px 15px 15px;
      text-align: center;
    }
  }
}
</style>